package app.sceledroid.network;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import app.sceledroid.entity.Course;
import app.sceledroid.entity.Deadline;

public class DeadlineGrabber extends
		AsyncTask<Document, Integer, ArrayList<Deadline>> {

	private Context context;
	private HttpClient client;
	private Course course;
	//private ArrayList<Deadline> deadlines;

	public DeadlineGrabber(Course course, Context context, HttpClient client) {
		super();
		this.context = context;
		this.course = course;
		this.client = client;
		//deadlines = new ArrayList<Deadline>();
	}

	@Override
	protected ArrayList<Deadline> doInBackground(Document... params) {
		// TODO Auto-generated method stub
		// String url = params[0];
		ArrayList<Deadline> deadlines = new ArrayList<Deadline>();
		course.setDeadlines(deadlines); 
		DateFormat df = new SimpleDateFormat("EEEE, d MMM yyyy, hh:mm a");
		Document doc = params[0];
		Elements elements = doc.select("li.assignment a");
		for (Element el : elements) {
			
			try {
				String href = el.attr("href");

				String dName = el.text();

				HttpGet request = new HttpGet(href);

				HttpResponse response = client.execute(request);
				InputStream stream = response.getEntity().getContent();

				Document deadlineDocument = Jsoup.parse(stream, "UTF-8", href);
				Element info = deadlineDocument.select("div#intro").first();
				Elements dates = deadlineDocument.select("td.c1");
				//Elements existingFiles = deadlineDocument.se
				Elements noSubmission = deadlineDocument.select("h3.main");
				
				String deadlineInfo = info.text();
				String tempdate = dates.get(0).text();
				
				Date from = df.parse(tempdate);
				tempdate = dates.get(1).text();
				Date to = df.parse(tempdate);
				
				Deadline deadline = new Deadline(dName, from, to, href, deadlineInfo);
				Log.v("DEADLINE", dName);
				if(deadlines != null)
				deadlines.add(deadline);
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				Log.v("DeadlineGrabber", e.getMessage());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.v("DeadlineGrabber", e.getMessage());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return course.getDeadlines();
	}

}
